package com.it.common.view

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Canvas
import android.graphics.Outline
import android.graphics.Path
import android.graphics.RectF
import android.util.AttributeSet
import android.view.View
import android.view.ViewOutlineProvider
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.content.res.ResourcesCompat
import com.yili.common.R

/**
 * @author Weiss
 * @description 自定义四个角弧度的ConstraintLayout，只支持同时设置四个角的弧度而不支持单独设置某个角的弧度
 */
class RoundedConstraintLayout(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : ConstraintLayout(context, attrs, defStyleAttr) {
    private var radius = 0.0f
    private val path: Path = Path()
    private var rect: RectF? = null

    constructor(context: Context) : this(context, null)

    @SuppressLint("Recycle", "CustomViewStyleable")
    constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0) {
        val typedArray = context.obtainStyledAttributes(attrs, R.styleable.roundedCorner)
        radius = typedArray.getDimension(R.styleable.roundedCorner_radius, 0F)
        val enableRipple = typedArray.getBoolean(R.styleable.roundedCorner_enableRipple, false)
        // 允许剪裁到轮廓
        clipToOutline = true
        outlineProvider = object : ViewOutlineProvider() {
            override fun getOutline(view: View?, outline: Outline?) {
                outline?.setRoundRect(0, 0, view?.width ?: 0, view?.height ?: 0, radius)
            }
        }
        typedArray.recycle()
        if (enableRipple) {
            val attrForeground = intArrayOf(android.R.attr.selectableItemBackground)
            val typed = context.obtainStyledAttributes(attrForeground)
            val foregroundResId = typed.getResourceId(0, 0)
            typed.recycle()
            ResourcesCompat.getDrawable(context.resources, foregroundResId, context.theme)?.let {
                foreground = it
            }
        }
    }

    @SuppressLint("DrawAllocation")
    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)
        if (radius > 0) {
            rect = RectF(0f, 0f, width.toFloat(), height.toFloat())
            path.addRoundRect(rect!!, radius, radius, Path.Direction.CW)
            canvas!!.clipPath(path)
        }
    }
}